package gw.com.android.ui.home;

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import java.util.List;

import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.ui.MainActivity;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.android.utils.PackStatis;
import gw.com.android.utils.ServerConnnectUtil;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.CommonUtils;
import www.com.library.util.DeviceUtil;
import www.com.library.util.NetworkMonitor;

/**
 * 首页自选产品的展示页
 * @author jett
 * @since 2017-11-21.
 */
public class ProductPagerAdapter extends PagerAdapter {

    private static final int PAGE_SIZE = 3;

    private final Activity mActivity;
    private final String mZoneType;
    private DataItemResult mList;
    private SparseArray<ProductionContainer> pagerViews = new SparseArray<>();
    private Typeface fontType;

    ProductPagerAdapter(Activity activity, String mZoneType) {
        this.mActivity = activity;
        this.mZoneType = mZoneType;
        if (mZoneType.equals(GTSConst.ZONE_TYPE_SELF + "")) {
            mList = DataManager.instance().getSelfTickList();
        } else {
            mList = DataManager.instance().getTickList(mZoneType);
        }
        fontType = Typeface.createFromAsset(activity.getResources().getAssets(), "fonts/DIN_Medium.ttf");
    }

    /**
     * 刷新界面排序后的数据
     */
    public void refreshSortData() {
        if (mZoneType.equals(GTSConst.ZONE_TYPE_SELF + "")) {
            mList = DataManager.instance().getSelfTickList();
        } else {
            mList = DataManager.instance().getTickList(mZoneType);
        }
        notifyDataSetChanged();
    }

    public void refreshData(DataItemDetail data) {
        if (data == null || mList == null) {
            return;
        }
        int code = data.getInt(GTSConst.JSON_KEY_CODEID);
        if (code == 0) {
            return;
        }
        List<DataItemDetail> dataList = mList.getDataList();
        int index = -1;
        if (dataList != null && !dataList.isEmpty()) {
            for (int i = 0; i < dataList.size(); i++) {
                DataItemDetail item = dataList.get(i);
                int itemCode = item.getInt(GTSConst.JSON_KEY_CODEID);
                if (code == itemCode) {
                    index = i;
                    break;
                }
            }
        }
        if (index >= 0) {
            int position = getPageByIndex(index);
            ProductionContainer container = pagerViews.get(position);
            if (container != null) {
                container.refresh(code, data);
            }
        }
    }

    private int getPageByIndex(int index) {
        return index / PAGE_SIZE;
    }

    @Override
    public int getCount() {
        if (mList != null) {
            int dataCount = mList.getDataCount();
            if (dataCount <= 0) {
                return 1;
            }
            return dataCount / PAGE_SIZE + 1;
        }
        return 1;
    }

    private List<DataItemDetail> getDataByPosition(int position) {
        if (mList == null || mList.getDataCount() <= 0) {
            return null;
        }
        List<DataItemDetail> dataList = mList.getDataList();
        if (dataList != null && !dataList.isEmpty()) {
            int startIndex = position * PAGE_SIZE;
            int endIndex = startIndex + PAGE_SIZE;
            if (startIndex > dataList.size() - 1) {
                return null;
            }
            if (endIndex > dataList.size()) {
                endIndex = dataList.size();
            }
            return dataList.subList(startIndex, endIndex);
        }
        return null;
    }

    private boolean isLastPage(int position) {
        return position == getCount() - 1;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        List<DataItemDetail> datas = getDataByPosition(position);
        ProductionContainer pager = new ProductionContainer(mActivity);
        pager.setData(datas);
        int dataCount = datas == null ? 0 : datas.size();
        if (dataCount < PAGE_SIZE && isLastPage(position)) {
            pager.addFootView(position);
        }
        container.addView(pager);
        pagerViews.put(position, pager);
        return pager;
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        return POSITION_NONE;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        pagerViews.removeAt(position);
        container.removeView((View) object);
    }

    private class ProductionContainer extends LinearLayout {

        private SparseArray<View> itemViews = new SparseArray<>();
        private final int itemWidth;
        private final LayoutInflater inflater;

        ProductionContainer(Context context) {
            super(context);
            setOrientation(HORIZONTAL);
            inflater = LayoutInflater.from(context);
            itemWidth = DeviceUtil.instance().getScreenPixelsWidth(context) / PAGE_SIZE;
        }

        void setData(List<DataItemDetail> data) {
            removeAllViews();
            if (data == null || data.isEmpty()) {
                return;
            }
            for (DataItemDetail item : data) {
                View child = inflater.inflate(R.layout.list_item_home_quote, this, false);
                ItemViewHolder holder = new ItemViewHolder(child);
                holder.bindData(item);
                int code = item.getInt(GTSConst.JSON_KEY_CODEID);
                itemViews.put(code, child);
                LayoutParams params = new LayoutParams(itemWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
                addView(child, params);
            }
        }

        void refresh(int code, DataItemDetail data) {
            View view = itemViews.get(code);
            if (view != null) {
                ItemViewHolder holder = (ItemViewHolder) view.getTag();
                holder.bindData(data);
            }
        }

        void addFootView(int position) {
            int footWidth = itemWidth;
            if ((itemViews == null || itemViews.size() <= 0) && position == 0) {
                footWidth = footWidth * PAGE_SIZE;
            }
            View footer = inflater.inflate(R.layout.list_footview_home_quote_item, this, false);
            LayoutParams params = new LayoutParams(footWidth, DeviceUtil.instance().dip2px(120, getContext()));
            //params.gravity = Gravity.CENTER;
            addView(footer, params);
            footer.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    PackStatis.getToService("clickadd", PackStatis.EventCategory.HOME.getValue(), null, null);
                    /*if (mActivity instanceof MainActivity) {
                        if (ServerConnnectUtil.instance().hasReConnectQuote()) {
                            return;
                        }
                        ((MainActivity) mActivity).setTabFragment(ConfigType.TAB_QUOTE_TAG, "");
                    }*/
                    ActivityManager.showQuoteSelfAddActivity(mActivity);
                }
            });
        }

    }

    private class ItemViewHolder {
        private View mRoot;
        TextView tvPercentView;
        ImageView ivPercentTriangle;
        TextView tvProductName;
        TextView tvNewPrice;
        ImageView ivPriceArrow;
        TextView tvRisePrice;

        ItemViewHolder(View root) {
            mRoot = root;
            tvPercentView = mRoot.findViewById(R.id.percent_view);
            ivPercentTriangle = mRoot.findViewById(R.id.percent_triangle);
            tvProductName = mRoot.findViewById(R.id.product_name);
            tvNewPrice = mRoot.findViewById(R.id.new_price);
            ivPriceArrow = mRoot.findViewById(R.id.new_price_arrow);
            tvRisePrice = mRoot.findViewById(R.id.rise_view);
            if (fontType != null) {
                tvNewPrice.setTypeface(fontType);
                tvPercentView.setTypeface(fontType);
            }
            mRoot.setTag(this);
        }

        void bindData(final DataItemDetail data) {
            if (data == null) {
                return;
            }
            tvProductName.setText(DataManager.instance().getPrdName(data));
            //涨幅
            int statu = AppContances.PRICE_UNCHANGE;
            if (data.getString(GTSConst.JSON_KEY_PERCENT).startsWith("-")) {
                statu = AppContances.PRICE_DECREASE;
            } else if (data.getString(GTSConst.JSON_KEY_PERCENT).startsWith("+")) {
                statu = AppContances.PRICE_INCREASE;
            }
            tvPercentView.setText(data.getString(GTSConst.JSON_KEY_PERCENT).concat("%"));
            ColorThemeUtil.instance().setPriceColor(tvPercentView, statu);
            /*int triangleIcon = ColorThemeUtil.instance().getPercentTriangleIcon(statu);
            if (triangleIcon == 0) {
                ivPercentTriangle.setVisibility(View.GONE);
            } else {
                ivPercentTriangle.setImageResource(triangleIcon);
            }*/
            //涨幅
            /*statu = AppContances.PRICE_UNCHANGE;
            if (data.getString(GTSConst.JSON_KEY_RISE).startsWith("-")) {
                statu = AppContances.PRICE_DECREASE;
            } else if (data.getString(GTSConst.JSON_KEY_RISE).startsWith("+")) {
                statu = AppContances.PRICE_INCREASE;
            }*/
            //tvRisePrice.setText(data.getString(GTSConst.JSON_KEY_RISE));
            //ColorThemeUtil.instance().setPriceColor(tvRisePrice, statu);
            // 现价
            tvNewPrice.setText(data.getString(GTSConst.JSON_KEY_CURPRICE));
            ivPriceArrow.setVisibility(View.GONE);
            //ColorThemeUtil.instance().setNewPriceColor(tvNewPrice, data.getInt(GTSConst.JSON_KEY_CURPRICESTATE), data.getInt(GTSConst.JSON_KEY_CURPRICEARRAW), true);
            ColorThemeUtil.instance().setNewPriceColor(tvNewPrice, ivPercentTriangle, data.getInt(GTSConst.JSON_KEY_CURPRICESTATE), data.getInt(GTSConst.JSON_KEY_CURPRICEARRAW));

            mRoot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onProductClick(data);
                }
            });
        }

        private void onProductClick(DataItemDetail data) {
            if (CommonUtils.isFastDoubleClick()) {
                return;
            }
            if (!NetworkMonitor.hasNetWork()) {
                return;
            }
            if (!ServerConnnectUtil.instance().isTradeConnect || !ServerConnnectUtil.instance().isQuoteConnect) {
                ServerConnnectUtil.instance().reConnectServerConfirm(mActivity);
                return;
            }
            if (null == data) {
                Logger.i("行情数据对象为空！！！");
                showErrorMsg(ConfigType.SERVER_ERROR_1021);
                return;
            }
            PackStatis.getToService(PackStatis.EventAction.CLICKPRODUCT.getValue(), PackStatis.EventCategory.HOME.getValue(), null, data.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME));

            //同时要打开 被点击产品的图表界面
            ActivityManager.showChartActivity(mActivity, data.getInt(GTSConst.JSON_KEY_CODEID), data.getInt(GTSConst.JSON_KEY_ZONE), AppContances.TRADE_TYPE_FORM_HOME);

            AppMain.getApp().getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mActivity instanceof MainActivity) {//至于这里要不要首页要不要切到 行情tab，emmmm...好的，依然切过去
                        ((MainActivity) mActivity).setTabFragment(ConfigType.TAB_QUOTE_TAG, "");
                    }
                }
            },800);



        }

        private void showErrorMsg(String errorId) {
            final PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(mActivity, "", ConfigUtil.instance().getErrorConfigObject().optString(errorId));
            dialog.show();
        }

    }

}
